package com.gongpingjialoan.adapter;

import android.annotation.SuppressLint;
import android.content.Context;
import android.content.Intent;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.bumptech.glide.Glide;
import com.gongpingjialoan.R;
import com.gongpingjialoan.activity.car.BuyCarVipActivity;
import com.gongpingjialoan.api.API;
import com.gongpingjialoan.api.Piont;
import com.gongpingjialoan.bean.CarSource;
import com.gongpingjialoan.manage.PointRecordManage;
import com.gongpingjialoan.network.NetDataJson;
import com.gongpingjialoan.utility.UserLocation;
import com.gongpingjialoan.utility.Utils;

import org.json.JSONException;
import org.json.JSONObject;

import java.text.DecimalFormat;
import java.util.List;

import static com.gongpingjialoan.R.id.model_zh;

public class CarSourceListAdapter extends BaseAdapter {

    //    private ForegroundColorSpan priceForegroundColorSpan;
    private String selectCarId = "null";

    private LayoutInflater mInflater;

    private Context context;

    public List<CarSource> mCarSourceList;

    private DecimalFormat df = new DecimalFormat("0.0000");

    private DecimalFormat df1 = new DecimalFormat("0.0");

    //1代表车市列表
    int type = 0;

    public CarSourceListAdapter(Context context) {
        this.context = context;
        mInflater = LayoutInflater.from(context);
//        priceForegroundColorSpan = new ForegroundColorSpan(context.getResources().getColor(R.color.button_normal_color));
    }

    public CarSourceListAdapter(Context context, int type) {
        this.type = type;
        this.context = context;
        mInflater = LayoutInflater.from(context);
//        priceForegroundColorSpan = new ForegroundColorSpan(context.getResources().getColor(R.color.button_normal_color));
    }


    public void setData(List<CarSource> CarSourceList) {
        this.mCarSourceList = CarSourceList;
        notifyDataSetChanged();
    }

    @Override
    public int getCount() {
        if (mCarSourceList == null) {
            return 0;
        }

        if (type == 1) {
            return mCarSourceList.size() + mCarSourceList.size() / 10;
        } else {
            return mCarSourceList.size();
        }

    }


    public void setCarId(String selectCarId) {
        this.selectCarId = selectCarId;
    }


    @Override
    public Object getItem(int position) {
        return null;
    }

    @Override
    public long getItemId(int position) {

        return 0;
    }

    @Override
    public int getViewTypeCount() {
        if (type == 1) {
            return 2;
        }
        return 1;
    }

    @Override
    public int getItemViewType(int position) {

        if (type == 1 && (position - 10) % 11 == 0) {
            return 1;
        } else {
            return 0;
        }
    }

    @SuppressLint("InflateParams")
    @Override
    public View getView(final int position, View convertView, ViewGroup parent) {
        CarSourceViewHolder holder = null;
        boolean isotherview = getItemViewType(position) == 1 ? true : false;
        if (convertView == null) {
            if (isotherview) {
                convertView = mInflater.inflate(R.layout.item_carlist_other, null);
            } else {
                convertView = mInflater.inflate(R.layout.car_list_item, null);
                holder = new CarSourceViewHolder();
                holder.brandname = (TextView) convertView.findViewById(R.id.brand_name);
                holder.yanTextView = (TextView) convertView.findViewById(R.id.yan);
                holder.imgThumbnail = (ImageView) convertView.findViewById(R.id.pic);
                holder.renzhengImageView = (ImageView) convertView.findViewById(R.id.renzheng);
                holder.tvCarTitle = (TextView) convertView.findViewById(R.id.carName);
                holder.pushTextView = (TextView) convertView.findViewById(R.id.push_time);
                holder.tvCarPrice = (TextView) convertView.findViewById(R.id.price);
                holder.tuihuanImageView = (TextView) convertView.findViewById(R.id.tuihuan_img);
                holder.shiguImageView = (TextView) convertView.findViewById(R.id.shigu_img);
                holder.index_txt = (TextView) convertView.findViewById(R.id.index_txt);
                holder.reviewTextView = (TextView) convertView.findViewById(R.id.review);
                holder.timeTextView = (TextView) convertView.findViewById(R.id.time);
                holder.typeTextView = (TextView) convertView.findViewById(R.id.type);
                holder.zhibaoImageView = (ImageView) convertView.findViewById(R.id.zhibao_view);
                holder.hyImageView = (ImageView) convertView.findViewById(R.id.hy_view);
                holder.downView = convertView.findViewById(R.id.yijiang_linear);
                holder.distance = (TextView) convertView.findViewById(R.id.distance);
                holder.downTypeTextView = (TextView) convertView.findViewById(R.id.zhang_jiang);
                holder.downPriceTextView = (TextView) convertView.findViewById(R.id.cut_price_id);
                holder.select_TextView = (TextView) convertView.findViewById(R.id.gangcai_id);
                holder.select_view = convertView.findViewById(R.id.right_view);
                holder.interestsView = (TextView) convertView.findViewById(R.id.interests);
                holder.interests_layout = (LinearLayout) convertView.findViewById(R.id.interests_layout);
                convertView.setTag(R.id.tag_first, holder);
            }
        } else {
            if (!isotherview) {
                holder = (CarSourceViewHolder) convertView.getTag(R.id.tag_first);
            }

        }

        int newposition = 0;
        if (position / 10 > 1) {
            newposition = position - position / 10;
        } else {
            newposition = position;
        }

        if (!isotherview && mCarSourceList.size() > newposition) {
            final CarSource source = mCarSourceList.get(newposition);
            convertView.setTag(R.id.tag_second, source);

            if (!TextUtils.isEmpty(source.distance) && UserLocation.getInstance().getCity().equals(source.mCity)) {
                holder.distance.setVisibility(View.VISIBLE);
                double distance = Double.parseDouble(source.distance) / 1000;
                holder.distance.setText(df1.format(distance) + "km");
            } else {
                holder.distance.setVisibility(View.GONE);
            }

            if ("false".equals(source.review)) {
                holder.reviewTextView.setVisibility(View.GONE);
            } else {
                holder.reviewTextView.setText("已下架");
                holder.reviewTextView.setVisibility(View.VISIBLE);
            }

            if (source.isactive) {
                holder.hyImageView.setVisibility(View.VISIBLE);
            } else {
                holder.hyImageView.setVisibility(View.GONE);
            }

            if ((mCarSourceList.get(newposition).mId + "").equals(selectCarId)) {
                holder.select_view.setBackgroundResource(R.color.select_list_bg);
                holder.select_TextView.setVisibility(View.VISIBLE);
            } else {
                holder.select_view.setBackgroundResource(R.drawable.trans);
                holder.select_TextView.setVisibility(View.GONE);
            }

            if (source.is_certify) {
                if ("4s".equals(source.dealer_category)) {
                    holder.renzhengImageView.setImageResource(R.drawable.renzheng_4s);
                } else {
                    holder.renzhengImageView.setImageResource(R.drawable.renzheng);
                }

                //
//            if (type == 1) {
                holder.renzhengImageView.setVisibility(View.GONE);
//            } else {
//                holder.renzhengImageView.setVisibility(View.VISIBLE);
//            }

            } else {
                holder.renzhengImageView.setVisibility(View.GONE);
            }

            if (source.cs_clean) {
                holder.yanTextView.setVisibility(View.VISIBLE);
            } else {
                holder.yanTextView.setVisibility(View.GONE);
            }

            if (source.mQsTags.contains("质保")) {
                holder.zhibaoImageView.setVisibility(View.VISIBLE);
                holder.typeTextView.setVisibility(View.GONE);
            } else {
                holder.zhibaoImageView.setVisibility(View.GONE);
                holder.typeTextView.setVisibility(View.VISIBLE);
                if ("personal".equals(source.mSourceType)) {
                    holder.typeTextView.setText("个");
                    holder.typeTextView.setBackgroundResource(R.drawable.sort_ge);
                    holder.typeTextView.setTextColor(context.getResources().getColor(R.color.white));
                } else if ("dealer".equals(source.mSourceType) || "cpo".equals(source.mSourceType) || "odealer".equals(source.mSourceType)) {
                    holder.typeTextView.setText("商");
                    holder.typeTextView.setBackgroundResource(R.drawable.sort_shang);
                    holder.typeTextView.setTextColor(context.getResources().getColor(R.color.white));
                } else {
                    holder.typeTextView.setVisibility(View.GONE);
                }
            }


//            当前标价15万，未降过价（只有首次标价 or 首次标价=最低标价）
//            当前标价15万，可降价0.5万（当前标价>=首次标价 and 当前标价>最低标价）
//            当前标价15万，已降价0.5万（当前标价<首次标价 and 当前标价=最低标价）
//            当前标价15万，已降价0.5万，还可降0.1万（当前标价<首次标价 and 当前标价>最低标价）
            int price_text;
            if (TextUtils.isEmpty(source.last_price)) {
                holder.downView.setVisibility(View.GONE);
//            cut_priceTextView.setText("首次标价");
            } else {
                double current_p = Double.valueOf(source.mPrice);
                double origin_p = Double.valueOf(source.origin_price);
                double lowest_p = Double.valueOf(source.lowest_price);
                holder.downView.setVisibility(View.GONE);
                if (current_p >= origin_p && current_p > lowest_p) {
                    holder.downView.setVisibility(View.VISIBLE);
                    price_text = (int) (Double.valueOf(df.format(current_p - lowest_p)) * 10000);
                    holder.downTypeTextView.setText("可降");
                    holder.downPriceTextView.setText(price_text + "元");
                    holder.downTypeTextView.setBackgroundResource(R.drawable.yi_jiang_green);
                    holder.downTypeTextView.setTextColor(context.getResources().getColor(R.color.new_color));
                    holder.downPriceTextView.setBackgroundResource(R.drawable.jiang_green);
                }
                if (current_p < origin_p && current_p == lowest_p) {
                    holder.downView.setVisibility(View.VISIBLE);
                    price_text = (int) (Double.valueOf(df.format(origin_p - current_p)) * 10000);
                    holder.downTypeTextView.setText("已降");
                    holder.downPriceTextView.setText(price_text + "元");
                    holder.downTypeTextView.setBackgroundResource(R.drawable.ke_jiang);
                    holder.downTypeTextView.setTextColor(context.getResources().getColor(R.color.c27));
                    holder.downPriceTextView.setBackgroundResource(R.drawable.ke_jiang_bg);
                }
                if (current_p < origin_p && current_p > lowest_p) {
                    holder.downView.setVisibility(View.VISIBLE);
                    price_text = (int) (Double.valueOf(df.format(current_p - lowest_p)) * 10000);
                    holder.downTypeTextView.setText("可降");
                    holder.downPriceTextView.setText(price_text + "元");
                    holder.downTypeTextView.setBackgroundResource(R.drawable.yi_jiang_green);
                    holder.downTypeTextView.setTextColor(context.getResources().getColor(R.color.new_color));
                    holder.downPriceTextView.setBackgroundResource(R.drawable.jiang_green);
                }
            }

            // convertView.setTag();
            holder.brandname.setText(source.model_zh);
            if (source.isViewed) {
                holder.brandname.setTextColor(context.getResources().getColor(R.color.discount_price_title));
            } else {
                holder.brandname.setTextColor(context.getResources().getColor(R.color.discount_title));
            }
            String msg = "";
            if (TextUtils.isEmpty(source.newCity)) {
                msg = "年上牌";
            } else {
                msg = "年上牌/" + source.newCity;
            }
            holder.timeTextView.setText(source.getmMile() + "万公里/" + source.getmYear() + msg);
            if ("".equals(source.model_detail_zh)) {
                holder.tvCarTitle.setText(source.getmTitle());
            } else {
                holder.tvCarTitle.setText(source.model_detail_zh);
            }
            holder.tvCarPrice.setText(String.valueOf(source.mPrice));


            holder.index_txt.setVisibility(View.VISIBLE);
            double index = source.mGpjIndex;
            if (index < 7) {
                holder.index_txt.setText("不推荐");
                holder.index_txt.setTextColor(context.getResources().getColor(R.color.bad_color));
                holder.index_txt.setBackgroundResource(R.drawable.bad_bg);
                holder.index_txt.setVisibility(View.GONE);
            } else if (index < 9 && index >= 7) {
                holder.index_txt.setText("一般");
                holder.index_txt.setTextColor(context.getResources().getColor(R.color.yiban_color));
                holder.index_txt.setBackgroundResource(R.drawable.yiban_bg);
                holder.index_txt.setVisibility(View.GONE);
            } else {
                holder.index_txt.setVisibility(View.VISIBLE);
                holder.index_txt.setText("超值");
                holder.index_txt.setTextColor(context.getResources().getColor(R.color.tuijian_color));
                holder.index_txt.setBackgroundResource(R.drawable.tuijian_bg);
            }

            if (source.mQsTags.contains("可退换")) {
                holder.tuihuanImageView.setVisibility(View.VISIBLE);
            } else {
                holder.tuihuanImageView.setVisibility(View.GONE);
            }

            if (source.mQsTags.contains("无大事故")) {
                holder.shiguImageView.setVisibility(View.VISIBLE);
            } else {
                holder.shiguImageView.setVisibility(View.GONE);
            }

            String timetitle = Utils.getTimeByTimestamp(source.pub_timestamp, System.currentTimeMillis());
            holder.pushTextView.setText(timetitle);


            String uri = source.mUrl + "?imageMogr2/thumbnail/!50p";
            Glide.with(context).load(uri).placeholder(R.drawable.car_loading).centerCrop().crossFade().into(holder.imgThumbnail);
            if (source.isInterests){
                holder.interestsView.setText("已收藏");
                holder.interestsView.setTextColor(context.getResources().getColor(R.color.white));
                holder.interestsView.setBackgroundResource(R.drawable.fillet_5_blue_bg);
            }else {
                holder.interestsView.setText("感兴趣");
                holder.interestsView.setTextColor(context.getResources().getColor(R.color.blue_3fbbff));
                holder.interestsView.setBackgroundResource(R.drawable.fillet_5_blue_white_bg);
            }
            final int item_index = newposition;
            holder.interests_layout.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    if (source.isInterests){
                       del_interests(source.interests_id,item_index);
                    }else {
                        interests(source,item_index);
                    }

                }
            });
        } else {

            ImageView picI = (ImageView) convertView.findViewById(R.id.pic);
            picI.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View view) {
                    PointRecordManage.getInstance().addPoint(context, Piont.MarketVIP);
                    Intent vipit = new Intent(context, BuyCarVipActivity.class);
                    vipit.putExtra("from", "carlist");
                    context.startActivity(vipit);
                }
            });
            if (((position - 10) / 11) % 2 == 0) {
                picI.setImageResource(R.drawable.vip_one);
            } else {
                picI.setImageResource(R.drawable.vip_two);
            }
        }
        return convertView;

    }

    private void interests(CarSource source, final int index){
        NetDataJson netDataJson = new NetDataJson(new NetDataJson.OnStringListener() {
            @Override
            public void onDataJsonError(String errorMessage) {
                Toast.makeText(context, errorMessage, Toast.LENGTH_SHORT).show();
            }

            @Override
            public void onDataJsonUpdate(String json) {
                try {
                    JSONObject jo = new JSONObject(json);
                    if (jo == null) {
                        return;
                    }
                    mCarSourceList.get(index).isInterests = true;
                    mCarSourceList.get(index).interests_id = jo.getString("id");
                    notifyDataSetChanged();
                    Toast.makeText(context, "关注成功", Toast.LENGTH_SHORT).show();

                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }
        }, 1);
        netDataJson.setUrl(NetDataJson.DOMAIN_INTERESTS + API.interests);
        netDataJson.setUseOtherDomain(true);
        netDataJson.addParam("car_id",source.mId);
        netDataJson.addParam("year",source.mYear);
        netDataJson.addParam("brand",source.getBrand());
        netDataJson.addParam("brand_slug",source.brand_zh);
        netDataJson.addParam("model",source.getModel());
        netDataJson.addParam("model_slug",model_zh);
        netDataJson.addParam("model_detail",source.getModel_detail());
        netDataJson.addParam("detail_slug",source.model_detail_zh);
        netDataJson.addParam("price",source.getmPrice());
        netDataJson.addParam("mile",source.getmMile());
        netDataJson.addParam("thumbnail",source.getmThumbnail());

        netDataJson.request("post");
    }

    private void del_interests(String interests_id, final int index){
        if (TextUtils.isEmpty(interests_id)){
            return;
        }
        NetDataJson netDataJson = new NetDataJson(new NetDataJson.OnStringListener() {
            @Override
            public void onDataJsonError(String errorMessage) {
                Toast.makeText(context, errorMessage, Toast.LENGTH_SHORT).show();
            }

            @Override
            public void onDataJsonUpdate(String json) {
                    mCarSourceList.get(index).isInterests = false;
                    mCarSourceList.get(index).interests_id = "";
                    notifyDataSetChanged();
                    Toast.makeText(context, "已取消关注", Toast.LENGTH_SHORT).show();
            }
        }, 1);
        netDataJson.setUrl(NetDataJson.DOMAIN_INTERESTS + API.interests + interests_id + "/");
        netDataJson.setUseOtherDomain(true);
        netDataJson.request("delete");
    }

    public class CarSourceViewHolder {
        public ImageView imgThumbnail;

        public ImageView renzhengImageView;

        public ImageView hyImageView;

        public TextView brandname;

        public TextView reviewTextView;

        public TextView distance;

        public TextView tvCarTitle;

        public TextView select_TextView;

        public TextView typeTextView;

        public ImageView zhibaoImageView;

        public TextView tvCarPrice;

        public TextView pushTextView;

        public TextView tuihuanImageView;

        public TextView shiguImageView;

        public TextView index_txt;

        public TextView timeTextView;

        public TextView yanTextView;

        public View downView, select_view;

        public TextView downTypeTextView;

        public TextView downPriceTextView;

        public TextView interestsView;

        public LinearLayout interests_layout;
    }
}
